<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Log;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
define("PRODUCT", "Iot");
define("VERSION", "2018-01-20");
define("METHOD", "POST");
/**
 * 以下示例以华东2地域及其服务接入地址为例。您在设置时，需使用您的物联网平台地域和对应的服务接入地址。
 */
define("REGION_ID", "cn-shanghai");
define("HOST", "iot.".REGION_ID.".aliyuncs.com");

/**
 * 示例接口
 */
class Switcher extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $productKey = 'a1Vb6SCOkfF';
    protected $accessKeyId = 'LTAI5tSeywRVianAvL3pqwT1';
    protected $accessSecret = 'BZTXzUo6mHlrglBKzvOE4W1yzZX4ak';


    private function print($msg)
    {
        LOG::write($msg,'info');
    }
    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        $this->success('返回成功', $this->request->param());
    }
/***
 * received topic=/sys/a1Vb6SCOkfF/switcher00002/thing/service/property/set, 
 * payload={"method":"thing.service.property.set","id":"2109170119","params":{"PowerSwitch_1":0},"version":"1.0.0"}
 * 
 * ***/
    public function switch_control() {
        $ret = 0;
        $msg="下发成功";
        $devid = $this->request->get("devicename", '');
        $on = $this->request->get("on", '');
        $this->print("devicename=".$devid.",on=".$on);

        // 设置一个全局客户端
        try {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
                ->regionId('cn-shanghai')
                ->asDefaultClient();
        } catch (ClientException $e) {
            LOG::write("Create AlibabaCloud Client Failed:".$e->getErrorMessage().PHP_EOL, "error");
            $this->error(__('Invalid parameters'));
        }

        $topic = '/sys/'.$this->productKey.'/'.$devid.'/thing/service/property/set';
        LOG::write("topic: ".$topic);
        $time =time();

        $msgContent = '{"method":"thing.service.property.set","id":"'.$time.'","params":{"PowerSwitch_1":'.$on.'},"version":"1.0.0"}';
        try {
            $query['RegionId'] = REGION_ID;
            $query['ProductKey'] = $this->productKey;
            $query['TopicFullName'] = $topic;
            $query['MessageContent'] = base64_encode($msgContent);
            $query['Qos'] = 1;

            $result = AlibabaCloud::rpc()
                        ->product('Iot')
                        ->method('POST')
                        ->version('2018-01-20')
                        ->host('iot.cn-shanghai.aliyuncs.com')
                        ->action('Pub')
                        ->options([
                            'query' => $query,
                        ])
                        ->request();
            $result2Array = $result->toArray();

            LOG::write($result2Array,'info');
            if (!$result2Array['Success']) {
                $msg = '发布消息失败'.PHP_EOL;
                LOG::write($msg,'error');
                $ret = -1;
            }
            else{
                LOG::write('发布消息成功' . PHP_EOL,'info');
            }
        } catch (ClientException $e) {
            $msg = $e->getErrorMessage() . PHP_EOL;
            LOG::write($msg,'error');
            $ret = -2;
        } catch (ServerException $e) {
            $msg = $e->getErrorMessage() . PHP_EOL;
            LOG::write($msg,'error');
            $ret = -3;
        }
        
        $result = [
            'ret' => $ret,
            'devicename' => $devid,
            'on' => $on
          ];
        
        if($ret == 0)
        {
            $ret = Db('devmgmt_switcher')->where('devicename', $devid)->update(['on' => $on,'updatetime'=>time()]);
            $this->print("ret is:".$ret);
        }

        $this->success('返回成功', ['result' => $result]);
    }

    public function getSwitchState()
    {
        $ret = 0;
        $result = NULL;
        $devicename = $this->request->get("devicename", '');
        $listData = Db('devmgmt_switcher')
                        ->where('devicename', $devicename)
                        ->select();

        foreach ($listData as $k => $v) {
            $result = array(
                "devicename" => $v['devicename'],
                "on" => $v['on'],
                "updatetime" => $v["updatetime"],
            );
        }
        
        $this->success('返回成功', ['result' => $result]);
    }
    
}
